package org.example.wx.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.example.wx.client.handler.NettyRPCReqHandler;

public class NettyClient {

    private Integer port;
    private String ipAddress;
    private EventLoopGroup eventLoopGroup;
    private Bootstrap bootStrap;

    NettyClient(String ipAddress, Integer port) {
        //调用的服务所在的端口
        this.port = port;
        //调用的服务所在的ip地址
        this.ipAddress = ipAddress;
        bootStrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup();
        bootStrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024, ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast(new NettyRPCReqHandler());
            }
        });


        try {
            ChannelFuture future = bootStrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }


    }


}
